package ccm.communicate.file;

import ccm.common.*;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileSaver implements ReceiveDataListener, StatusChangeListener
{
    static
    {
        final String var=System.getenv("MY_OUTPUT_DIR");
        if(var!=null&&!var.isEmpty())
        {
            CCMConfigManager.setStringIfAbsent("ccm/communicate/file/FileSaver/dir",var);
        }
    }

    protected OutputStream outputStream;
    protected String name;

    public FileSaver()
    {
        outputStream=null;
    }

    public static byte[] readAll(File file) throws IOException
    {
        byte[] buf=new byte[(int)file.length()];
        FileInputStream in=new FileInputStream(file);
        in.read(buf);
        in.close();
        return buf;
    }

    public void setFileSaverDir(String dir)
    {
        CCMConfigManager.setString("ccm/communicate/file/FileSaver/dir",dir);
        if(outputStream!=null)
        {
            restart();
        }
    }

    private void restart()
    {
        try
        {
            stop();
            if(!CCMConfigManager.getString("ccm/communicate/file/FileSaver/dir").isEmpty())
            {
                name=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
                final String dir=CCMConfigManager.getString("ccm/communicate/file/FileSaver/dir")+"/"+name+".receive";
                outputStream=Files.newOutputStream(new File(dir).toPath());
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    private void stop()
    {
        try
        {
            if(outputStream!=null)
            {
                outputStream.flush();
                outputStream.close();
            }
            outputStream=null;
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    String getInfoText()
    {
        if(outputStream==null)
        {
            return "未录制";
        }
        return "录制中"+name;
    }

    /**
     * 接收到数据事件
     *
     * @param event 事件
     */
    @Override
    synchronized public void receiveData(ReceiveDataEvent event)
    {
        if(outputStream!=null)
        {
            try
            {
                outputStream.write(event.getData());
            }catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取配置用的面板
     *
     * @return 配置用的面板
     */
    public JPanel getConfigJPanel()
    {
        return new FileSaverConfigJPanel(this);
    }

    @Override
    public void statusChange(StatusChangeEvent event)
    {
        if(event.getReason()==StatusChangeEvent.START)
        {
            restart();
        }
        if(event.getReason()==StatusChangeEvent.STOP)
        {
            stop();
        }
    }
}
